package com.heima.kafka.simple;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class ProducerStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //2.创建连接kafka配置信息
        Properties properties=new Properties();
            //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.140:9092");
            //key序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //重试配置
        properties.put(ProducerConfig.RETRIES_CONFIG,10);


        //1.创建生产者对象
        KafkaProducer producer = new KafkaProducer(properties);


        //3.发送消息
        /**
         * ProducerRecord(String topic, K key, V value)
         * 参数1表示发送消息的主题，也叫队列名称
         * 参数2表示发送消息的key
            参数3表示发送的消息内容
         */
        for (int i = 1; i <=5 ; i++) {
            if(i%2==0){
                ProducerRecord record=new ProducerRecord("kafka-stream-producer-topic","key"+i,"hello kafka");
                producer.send(record);
            }else{
                ProducerRecord record=new ProducerRecord("kafka-stream-producer-topic","key"+i,"hello itcast");
                producer.send(record);
            }

        }

     /*   producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception exception) {
                if(exception!=null){
                    throw new RuntimeException(exception);
                }
                System.out.println(metadata.offset());
            }
        });*/


        //4.释放资源，关闭通道
        producer.close();

    }
}
